#!/usr/bin/python
#coding:utf-8

from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests
from datetime import datetime
import demjson
import re

bot = Bot()

# linux执行登陆请调用下面的这句
bot = Bot(console_qr=True, cache_path=True)


def get_news():
    """获取金山词霸每日一句，英文和翻译"""

    url = "http://open.iciba.com/dsapi/"
    r = requests.get(url)
    content = r.json()['content']
    note = r.json()['note']
    return content, note


def get_books():
    """获取新浪新闻当天最热门资讯15条"""
    url = r'http://top.news.sina.com.cn/ws/GetTopDataList.php?top_type=day&top_cat=www_www_all_suda_suda&top_time={' \
          r'}&top_show_num=100&top_order=DESC&js_var=all_1_data01'.format(
        datetime.now().strftime("%Y%m%d"))
    try:
        response = requests.get(url).text
        jsondata = demjson.decode(re.compile(r'var all_1_data01 = (.*?);', re.S).findall(response)[0])
        news_lists = jsondata.get('data')[0:15]
        content = []
        s = '[玫瑰][玫瑰]今日最新资讯[玫瑰][玫瑰]\n'
        content.append(s)
        for new in range(0, len(news_lists)):
            e = str(new + 1) + '.' + ' ' + news_lists[new]['title']
            content.append(e)
        return '\n'.join(content)
    except:
        return ''


def send_news():
    try:
        contents = get_news()
        books = get_books()

        # 你朋友的微信名称，不是备注，也不是微信帐号。

        if contents and books:
            my_friend = bot.groups().search(u'1000小时读书计划')[0]
            my_friend.send(contents[0])
            my_friend.send(contents[1])
            my_friend.send(books)
            # 每86400秒（1天），发送1次
            t = Timer(60 * 60 * 24, send_news)
            t.start()
    except:

        # 你的微信名称，不是微信帐号。

        my_friend = bot.friends().search('程佳俊')[0]
        my_friend.send(u"今天消息发送失败了")


if __name__ == "__main__":
    send_news()

bot.join()
